<template>
  <div>
    <h1>计算属性和监听</h1>
    <input type="text" v-model="user.firstName"> <br />
    <input type="text" v-model="user.lastName"><br />
    <input type="text" v-model="user.child.lastName"><br />
    <input type="text" v-model="fullName1"><br />
    <input type="text" v-model="fullName2"><br />
    <input type="text" v-model="fullName3"><br />
    <input type="text" v-model="fullName4"><br />

  </div>
</template>

<script lang="ts">
// import { computed } from '@vue/reactivity';
import { defineComponent, reactive, computed, ref, watch, watchEffect } from 'vue';

export default defineComponent({
  setup() {
    const user = reactive({
      firstName: 'ni',
      lastName: 'an',
      child: {
        firstName: 'nini',
        lastName: 'anan',
      },
    });
    const fullName1 = computed(() => {
      return user.firstName + '-' + user.lastName;
    });
    console.log(fullName1);

    const fullName2 = computed({
      get() {
        return user.firstName + '-' + user.lastName;
      },
      set(value: string) {
        console.log(value);
        const arr = value.split('-');
        user.firstName = arr[0];
        user.lastName = arr[1];

      },
    });
    const fullName3 = ref('');
    watch(
      [fullName3, () => user.firstName, () => user.lastName],
      (values, oldValues) => {
        console.log(values);
        console.log(oldValues);
        if (values[1] != oldValues[1] || values[2] != oldValues[2]) {
          fullName3.value = values[1] + '-' + values[2];
        } else if (values[0] != oldValues[1]) {
          let arr = values[0].split('-');
          user.firstName = arr[0];
          user.lastName = arr[1];
        }


      }
    );

    const fullName4 = ref('');
    watchEffect(() => {
      fullName4.value = user.firstName + '-' + user.lastName;
    });

    return {
      user,
      fullName1,
      fullName2,
      fullName3,
      fullName4,
    };
  },
});
</script>

<style scoped>

</style>
